/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.imsx.viss;

import com.basho.riak.client.api.RiakClient;
import com.basho.riak.client.api.commands.kv.FetchValue;
import com.basho.riak.client.api.commands.kv.StoreValue;
import com.basho.riak.client.core.query.Location;
import com.basho.riak.client.core.query.Namespace;
import com.imsx.controller.util.ConexionRiak;
import com.imsx.model.Cliente;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author pablo
 */
public class DAOUsuario {

    //Parametro de diseño Singleton 

    static DAOUsuario instancia;

    private DAOUsuario() {
    }

    public static DAOUsuario getInstancia() {
        if (instancia == null) {
            instancia = new DAOUsuario();
        }

        return instancia;
    }

    public void Registrar(Cliente user) throws ExecutionException, InterruptedException {

        ConexionRiak conexion = new ConexionRiak();
        RiakClient client = conexion.conectar();
        Namespace usuariosBucket = new Namespace("cliente");
        Location usuarioLocacion = new Location(usuariosBucket, user.getCorreo());
        StoreValue storeUsuario = new StoreValue.Builder(user)
                .withLocation(usuarioLocacion)
                .build();
        client.execute(storeUsuario);
        conexion.cerrar();
    }

    public Cliente obtener(String correo) {
        try {
            ConexionRiak conexion = new ConexionRiak();
            RiakClient client = conexion.conectar();
            Namespace usuariosBucket = new Namespace("cliente");
            Location usuarioLocacion = new Location(usuariosBucket, correo);
            FetchValue fetchMobyDickOp = new FetchValue.Builder(usuarioLocacion)
                    .build();
            Cliente user = client.execute(fetchMobyDickOp).getValue(Cliente.class);
            System.out.println("User object successfully fetched");
            conexion.cerrar();
            return user;
        } catch (ExecutionException ex) {
            Logger.getLogger(DAOUsuario.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InterruptedException ex) {
            Logger.getLogger(DAOUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }

    public Cliente Validarlogueo(String contrasena, String correo) {
     Cliente c =obtener(correo);
     if(c!=null){
         if(contrasena.equalsIgnoreCase(c.getContrasena())){
            return c;
         }
     }
     return null;
    }
}
